#pragma once
#include <string>
#include <fstream>
#include <string>
#include <unordered_map>

#include "Log.hpp"
#include "InetAddr.hpp"

/*------------ 字典查找的实现 ---------------*/

std::string InitPath = "./dictionary.txt";
std::string set = ": ";

using namespace LogModule;

class Dict
{
public:
    Dict(std::string path = InitPath) : _path(path)
    {
    }

    bool LoadDict()
    {
        // 1、打开字典翻译文件
        std::ifstream in(_path); // 输入文件流
        if (!in.is_open())
        {
            LOG(LogLevel::ERROR) << "打开翻译文件失败";
            return false;
        }
        // 2、开始翻译
        std::string line; // 用于存储读取到的每一行内容
        while (std::getline(in, line))
        {
            // apple: 苹果
            auto pos = line.find(set);
            if (pos == std::string::npos)
            {
                LOG(LogLevel::ERROR) << "字典格式有误";
                continue;
            }
            // 找到数据，开始读取中英文
            std::string english = line.substr(0, pos);
            std::string chinese = line.substr(pos + set.size());
            if (english.empty() || chinese.empty())
            {
                LOG(LogLevel::ERROR) << "未找到";
                continue;
            }
            _dict.insert(std::make_pair(english, chinese));
            LOG(LogLevel::INFO) << "加载";
        }
        in.close();
        return true;
    }

    std::string Translate(const std::string &word, InetAddr &client)
    {
        auto iter = _dict.find(word);
        if (iter == _dict.end())
        {
            LOG(LogLevel::DEBUG) << "进入到了翻译模块, [" << client.Ip() << " : " << client.Port() << "]# " << word << "->None";
            return "None";
        }
        LOG(LogLevel::DEBUG) << "进入到了翻译模块, [" << client.Ip() << " : " << client.Port() << "]# " << word << "->" << iter->second;
        return iter->second;
    }

private:
    std::string _path;                                  // 路径 + 文件名
    std::unordered_map<std::string, std::string> _dict; // 存放字典的结构体
};
